<template>
  <view class="edit-page">
    <!-- 顶部导航栏 -->
    <view class="edit-header">
      <uni-icons type="arrowleft" size="24" color="#333" @click="goBack" />
      <text class="header-title">编辑个人信息</text>
      <text class="save-btn" @click="saveProfile">保存</text>
    </view>

    <view class="form-container">
      <!-- 头像上传 -->
      <view class="form-item">
        <text class="form-label">头像</text>
        <view class="avatar-upload" @click="changeAvatar">
          <image
            v-if="formData.avatar"
            :src="formData.avatar"
            mode="aspectFill"
            class="avatar-preview"
          />
          <view v-else class="avatar-upload-placeholder">
            <uni-icons type="camera" size="40" color="#999" />
          </view>
        </view>
      </view>

      <!-- 用户名 -->
      <view class="form-item">
        <text class="form-label">用户名</text>
        <input
          class="form-input"
          v-model="formData.username"
          placeholder="请输入用户名"
          placeholder-style="color: #ccc;"
        />
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <text class="form-label">手机号</text>
        <input
          class="form-input"
          v-model="formData.phoneNumber"
          placeholder="请输入手机号"
          placeholder-style="color: #ccc;"
          type="number"
        />
      </view>

      <!-- 个人介绍 -->
      <view class="form-item">
        <text class="form-label">个人介绍</text>
        <textarea
          class="form-textarea"
          v-model="formData.content"
          placeholder="请输入个人介绍"
          placeholder-style="color: #ccc;"
          maxlength="200"
        />
        <text class="textarea-count"
          >{{ formData.content ? formData.content.length : 0 }}/200</text
        >
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        avatar: "",
        username: "",
        phoneNumber: "",
        content: "",
      },
    };
  },
  onLoad() {
    this.getUserInfo();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    async getUserInfo() {
      try {
        const res = await uni.$http.get("/sys/user/updateInfo");
        if (res.statusCode === 200) {
          const userData = res.data.data;
          this.formData = {
            id: userData.id,
            avatar: userData.avatar || "",
            username: userData.username || "",
            phoneNumber: userData.phoneNumber || "",
            content: userData.content || "",
            status: 1,
          };
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        uni.showToast({
          title: "获取信息失败",
          icon: "none",
        });
      }
    },

    // 上传头像（选择后立即上传）
    async changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: async (res) => {
          const tempPath = res.tempFilePaths[0];
          uni.showLoading({ title: "上传中..." });

          try {
            // 上传文件
            const uploadRes = await uni.uploadFile({
              url: `${uni.$baseUrl}/file/upload`, // 你的接口
              filePath: tempPath,
              name: "file", // 必须和 @RequestParam("file") 一致
              header: {
                Authorization: uni.getStorageSync("authorization"), // 携带 token
              },
            });

            const data = JSON.parse(uploadRes[1].data);

            // 后端返回的是文件名，拼成完整地址
            // 假设你静态资源映射到 /avatar/
            const avatarUrl = `${uni.$baseUrl}/file/download?name=${data.message}`;
            // 修改用户信息
            this.formData.avatar = avatarUrl;
          } catch (e) {
            uni.showToast({ title: "网络错误", icon: "none" });
          } finally {
            uni.hideLoading();
          }
        },
      });
    },

    async saveProfile() {
      if (!this.formData.username) {
        uni.showToast({
          title: "请输入用户名",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "保存中...",
        });

        const res = await uni.$http.post("/sys/user/update", this.formData);

        uni.hideLoading();

        uni.showToast({
          title: "保存成功",
          icon: "success",
        });

        setTimeout(() => {
          uni.navigateBack();
        }, 500);
      } catch (error) {
        uni.hideLoading();
        console.error("保存失败:", error);
        uni.showToast({
          title: "保存失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-page {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.edit-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;

  .header-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .save-btn {
    font-size: 32rpx;
    color: #1e90ff;
    font-weight: 500;
  }
}

.form-container {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f1f2f6;
  display: flex;
  flex-direction: column;

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.form-input {
  font-size: 32rpx;
  padding: 20rpx 0;
  color: #333;
}

.avatar-upload {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border: 2rpx dashed #ddd;
}

.avatar-preview {
  width: 100%;
  height: 100%;
}

.avatar-upload-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 32rpx;
  box-sizing: border-box;
}

.textarea-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}
</style>
